ContractDetail = Ext.extend(Ext.Panel, {
    initComponent: function() {
        this.title = '===';
        this.id = 'ContractInfo';
        this.region = 'center';
        this.layout = 'border';
        this.margins = '0 0 0 0';
        //this.bodyStyle = 'background-color:#DFE8F6';
        this.border = false;
        this.frame = false;
        this.autoScroll = true;
        this.year = 2010;

        this.execAndPayGridH = parseInt(getCookie('execAndPayGridH'));
        this.execAndPayGridH =(this.execAndPayGridH) ? this.execAndPayGridH : 280;

        this.TitleLabel = new Ext.form.Label({cls: 'tbarLabel', text: ''});
        this.SummLabel = new Ext.form.Label({cls: 'tbarLabel', text: '0.00'});
        this.modeToggler1 = new Ext.Button({ xtype: 'tbbutton', text: 'Факт-План', disabled: true, handler: function() { this.ShowMode(0); }, scope: this });
        this.modeToggler2 = new Ext.Button({ xtype: 'tbbutton', text: 'Отработки-Оплаты', disabled: false, handler: function() { this.ShowMode(1); }, scope: this });
        this.tbar = [ {text: '&nbsp;'}, this.TitleLabel, {text: '&nbsp;'}, '-', {text: '&nbsp;'}, this.SummLabel, {text: '&nbsp;'},'-','->','-', this.modeToggler1,'-',this.modeToggler2 ];

        this.cellEditor =  Ext.extend(Ext.form.NumberField, {
            allowBlank: false,
            allowNegative: false,
            maxValue: 999999999999.99
        });
        this.moneyFormat = '0.00';
        this.curDocType =0;
        this.SelectedCell ={};

        //this.initLabelPanel();
        this.initWorksAndPaysPanel();
        this.initSummDetail();
        this.initFPanel();
        
        this.cnt_id=0;
        //this.on('activate', function() { this.execAndPayStore.baseParams = { contract_id: this.cnt_id}; }, this );

        this.items =  [ this.FPanel ];

        ContractDetail.superclass.initComponent.call(this);

    },
    initFPanel: function(){
        this.FPanel = new Ext.Panel({
            region:'center',
            layout:'border',
            border: false,
            items: [ this.execAndPayGrid, this.summDetailGrid ]
        });
    },
    initWorksAndPaysPanel: function() {

        this.execAndPayStore = new Ext.data.GroupingStore({
            reader: new Ext.data.JsonReader({
                root: 'data',
                fields:[
                { name: 'wap_id', type: 'int' },
                { name: 'wap_type_id', type: 'int' },
                { name: 'isplan', type: 'bool' },
                { name: 'contract_id', type: 'int' },
                { name: 'm01', type: 'number' },
                { name: 'm02', type: 'number' },
                { name: 'm03', type: 'number' },
                { name: 'm04', type: 'number' },
                { name: 'm05', type: 'number' },
                { name: 'm06', type: 'number' },
                { name: 'm07', type: 'number' },
                { name: 'm08', type: 'number' },
                { name: 'm09', type: 'number' },
                { name: 'm10', type: 'number' },
                { name: 'm11', type: 'number' },
                { name: 'm12', type: 'number' },
                { name: 'total', type: 'number' }]
            }),
            paramNames: { contract: 'contract' },
            baseParams: { contract_id: this.cnt_id},
            url: 'main?action=GetExecAndPay',
            groupField: 'isplan',
            sortInfo: { field: 'isplan', direction: 'ASC' },
            listeners: {
                scope: this,
                load: function(st) {
                    var cont = st.reader.jsonData.contract[0];
                    this.TitleLabel.setText('Контракт: '+cont.contract_name+' от '+cont.signing_date);
                    var cur_s_name = curencyStore.getAt(curencyStore.find('currency_id', cont.contract_currency_id)).data.s_name;
                    this.SummLabel.setText('Сумма контракта: '+cont.contract_summ+' '+cur_s_name);
                }
            }
        });

        Ext.ux.grid.GroupSummary.Calculations['totalSumm'] = function(v, record, field){
            return ( parseFloat(record.data.m01) + parseFloat(record.data.m02) +parseFloat(record.data.m03) + parseFloat(record.data.m04) +parseFloat(record.data.m05) + parseFloat(record.data.m06) +
                parseFloat(record.data.m07) + parseFloat(record.data.m08) + parseFloat(record.data.m09) + parseFloat(record.data.m10) + parseFloat(record.data.m11) + parseFloat(record.data.m12) );
        };
        Ext.ux.grid.GroupSummary.Calculations['sub'] = function(v, record, field){
            var tt; var st = record.store;
            if(record.store.groupField == 'isplan') {
                tt = ( record.data.wap_type_id == 2 ) ? -1 : 1;
            } else {
                tt = ( record.data.isplan ) ? -1 : 1;
            }
            var nn = sprintf('%01.2f',  parseFloat(v) + parseFloat( record.data[field] )*tt );
            return nn;
        };

        var summary = new Ext.ux.grid.GroupSummary();
        
        this.execAndPayGrid = new Ext.grid.GridPanel({
            title: 'План реализации',
            region: 'north',
            frame: false,
            border: true,
            height: 220,
            store: this.execAndPayStore,
            margins:'3 3 3 3',
            cmargins:'3 3 3 3',
            //height: this.execAndPayGridH,
            //split: true,
            loadMask: true,
            selModel: new Ext.grid.CellSelectionModel({}),
            colModel: new Ext.grid.ColumnModel({
                defaults: { width: 60, align: 'right' },
                columns: [
                    {header: 'Контракт', dataIndex: 'contract_id', hidden: true },
                    {header: '*', width: 60, css: 'color:#15428B; font:12px arial,tahoma,helvetica,sans-serif; font-weight:bold;', dataIndex: 'wap_type_id', summaryRenderer: function(v, params, data){ return 'Баланс:'; }, renderer: this.TypeCollRender },
                    {header: '*', width: 60, css: 'color:#15428B; font:12px arial,tahoma,helvetica,sans-serif; font-weight:bold;', dataIndex: 'isplan', summaryRenderer: function(v, params, data){ return 'Баланс:'; }, renderer: this.getPlanTitle },
                    {header: 'Январь', dataIndex: 'm01', summaryType: 'sub', renderer: this.paint},
                    {header: 'Февраль', dataIndex: 'm02', summaryType: 'sub', renderer: this.paint},
                    {header: 'Март', dataIndex: 'm03', summaryType: 'sub', renderer: this.paint},
                    {header: 'Апрель', dataIndex: 'm04', summaryType: 'sub', renderer: this.paint},
                    {header: 'Май', dataIndex: 'm05', summaryType: 'sub', renderer: this.paint},
                    {header: 'Июнь', dataIndex: 'm06', summaryType: 'sub', renderer: this.paint},
                    {header: 'Июль', dataIndex: 'm07', summaryType: 'sub', renderer: this.paint},
                    {header: 'Август', dataIndex: 'm08', summaryType: 'sub', renderer: this.paint},
                    {header: 'Сентябрь', dataIndex: 'm09', summaryType: 'sub', renderer: this.paint},
                    {header: 'Октябрь', dataIndex: 'm10', summaryType: 'sub', renderer: this.paint},
                    {header: 'Ноябрь', dataIndex: 'm11', summaryType: 'sub', renderer: this.paint},
                    {header: 'Декабрь', dataIndex: 'm12', summaryType: 'sub', renderer: this.paint},
                    {header: 'Итого', dataIndex: 'total', summaryType: 'totalSumm', renderer: this.total }
                ]
            }),
            view: new Ext.grid.GroupingView({
                forceFit: true,
                showGroupName: true,
                enableNoGroups: true,
		enableGroupingMenu: true,
                hideGroupedColumn: true,
                groupTextTpl: '&nbsp;{group}'
            }),
            plugins: summary,
            listeners: { scope: this,
                cellclick: function(gr, rowInd, colIdx, e) {
                    var rr = gr.store.getAt(rowInd);
                    if(!rr.data.isplan) {
                        var cm = gr.getColumnModel();
                        var mm = (cm.getColumnHeader(colIdx)=='Итого') ? 'год' : cm.getColumnHeader(colIdx);
                        this.curDocType = rr.data.wap_type_id;
                        var type = (this.curDocType=='2') ? 'оплаты' :'отработки';
                        this.summDetailGrid.setTitle('Детализация суммы '+type+' за '+mm);                        
                        this.SelectedCell = { RowIdx:rowInd, ColIdx: colIdx, dataIndex: cm.getDataIndex(colIdx)};
                        e.stopEvent();
                        this.getSummDetail(colIdx-2, this.curDocType);
                    }
                }
            }
        });
        this.execAndPayGrid.on('resize', function() { 
          setCookie('execAndPayGridH', this.getHeight());
        }, this.execAndPayGrid);
        this.WorksAndPaysPanel = new Ext.Panel({ region: 'center',layout: 'border', border: false, items: [ this.execAndPayGrid ] });
    },
    initSummDetail: function(){
        this.SummDetailTitle = new Ext.form.Label({cls: 'tbarLabel', text: '-'});
        this.rEditor = new Ext.ux.grid.RowEditor({ saveText: 'Сохранить', cancelText: 'Отменить', commitChangesText: 'Вы должны сохранить или отменить изменения в текущей записи.', errorText: 'Ошибка' });
        this.rEditor.on('beforeedit', function() { VP.getEl().mask();});
        this.rEditor.on('canceledit', function() { VP.getEl().unmask();});
        this.rEditor.on('afteredit', function() { VP.getEl().unmask();});
        this.curList = new Ext.form.ComboBox({
            name: 'currency_id',
            mode: 'local',
            emptyText: 'выбирете валюту',
            //store: curencyStore,
            valueField: 'currency_id',
            displayField: 's_name',
            triggerAction: 'all',
            listClass: 'x-combo-list-small',
            listeners: {
                scope: this,
                change: function(cb, new_val, old_val) {
                    var new_rate = 1;
                    if(new_val == 1) new_rate = 1.00;
                    if(new_val == 2) new_rate = 147.70;
                    if(new_val == 3) new_rate = 205.50;
                    this.rEditor.items.items[3].setValue(new_rate);
                }
            }

        });

        var summDetailRow = Ext.data.Record.create([
            { name: 'doc_id', type: 'string' },
            { name: 'doc_type_id', type: 'string' },
            { name: 'contract_id', type: 'string' },
            { name: 'date', type: 'data',dateFormat: 'n.j.Y' },
            { name: 'summ', type: 'string' },
            { name: 'currency_id', type: 'string' },
            { name: 'ch_rate', type: 'string' },
            { name: 'document', type: 'string' },
            { name: 'comment', type: 'string' }
        ]);

        this.summDetailStore = new Ext.data.JsonStore({
            autoDestroy: true,
            //autoLoad: true,
            url: 'main?action=GetContractDocuments',
            root: 'data',
            fields: ['doc_id', 'doc_type_id', 'contract_id', 'date', 'summ', 'currency_id', 'ch_rate', 'document', 'comment'],
            sortInfo: {field: 'date', direction: 'ASC'},
            listeners: {
                scope: this,
                //beforeload: function(st) { st.removeAll(true); },
                update: function(st, rec, op) {
                    //error_mes('Ошибка', op);
                    if(op=='edit') {

                    }
                    if(op=='commit') {
                        var data = rec.data;
                        if(!parseInt(data.currency_id)){
                            data.currency_id = curencyStore.getAt(curencyStore.find('s_name', data.currency_id)).data.currency_id;
                        }
                        Ext.Ajax.request({
                            url: 'main?action=AddDocument',
                            params: data,
                            scope: this,
                            callback: function(options, success, response) {
                                var ansv = Ext.decode(response.responseText);
                                if(ansv.success) {
                                    if(ansv.doc_id) {
                                        //rec.data.doc_id = ansv.doc_id;
                                    }
                                    this.updateSummCell(ansv.new_summ);
                                } else { error_mes('Ошибка',  ansv.error); }
                            }
                        });
                    }

                },
                load: function(st, recs, opts) {
                    //ddd = recs;
                }
            }
        });
        this.dateEditor = { xtype: 'datefield', allowBlank: false, minValue: '01.01.1990', maxValue: (new Date('2010 12 31')).format('d.m.Y')};
        this.summDetailGrid = new Ext.grid.EditorGridPanel({
            title: '---',
            region: 'center',
            frame: false,
            border: true,
            split: true,
            store: this.summDetailStore,
            margins:'0 3 3 3',
            cmargins:'0 3 3 3',
            loadMask: true,
            plugins: [this.rEditor],
            //tbar: [ this.SummDetailTitle ],
            bbar: [{
                icon: '/bres/img/butt_ico_16/add-icon.png',
                text: 'Добавить документ',
                handler: function(){
                    var new_date = this.year+ ' '+( (this.SelectedCell.ColIdx) ? this.SelectedCell.ColIdx-2: 1)+' 01';
                    var e = new summDetailRow({doc_id: '', doc_type_id: this.curDocType, contract_id:this.cnt_id, date: (new Date(new_date)).clearTime(), summ: 0, currency_id: '1', ch_rate: 1.00, document: 'Название документа', comment: '' });
                    this.rEditor.stopEditing();
                    this.summDetailStore.insert(0, e);
                    this.summDetailGrid.getView().refresh();
                    this.summDetailGrid.getSelectionModel().selectRow(0);
                    this.rEditor.startEditing(0);
                }, scope: this
            },'-',{
                ref: '../removeBtn',
                icon: '/bres/img/butt_ico_16/remove-icon.png',
                text: 'Удалить документ',
                handler: this.deleteDocument, scope: this
            },'->', {text: 'Сохранить изменения', icon: '/bres/img/butt_ico_16/accept-icon.png', handler: function() { this.summDetailStore.commitChanges(); }, scope: this }],

            colModel: new Ext.grid.ColumnModel({
                columns: [
                    {header: 'Дата', width: 85, dataIndex: 'date',editor: this.dateEditor, renderer: Ext.util.Format.dateRenderer( 'd.m.Y')},
                    {header: 'Сумма', align: 'right', width: 100, dataIndex: 'summ', editor: { xtype: 'numberfield', allowBlank: false, minValue: 0.00, maxValue: 99999999.99 }, renderer: Ext.util.Format.numberRenderer( this.moneyFormat)},
                    {header: 'Валюта', width: 60, dataIndex: 'currency_id',editor: this.curList,renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                          var val = value;
                          if(parseInt(value)) val = curencyStore.getAt(curencyStore.find('currency_id', value)).data.s_name;
                          return val;
                       }, scope: this },
                    {header: 'Курс', width: 60, dataIndex: 'ch_rate', editor: { xtype: 'numberfield', allowBlank: false, minValue: 0.00, maxValue: 99999.99 } },
                    {header: 'Документ', width: 250, dataIndex: 'document',editor: { xtype: 'textfield', allowBlank: false }},
                    {header: 'Коментарий', id: 'SummComment', dataIndex: 'comment',editor: { xtype: 'textfield' }}
                ]
            }),
            autoExpandColumn: 'SummComment',
            //viewConfig: { forceFit: true },
            sm: new Ext.grid.RowSelectionModel({
                singleSelect:true,
                listeners: { rowselect: function(sm, row, rec) { } }
            })
        });
        this.summDetailGrid.getSelectionModel().on('selectionchange', function(sm){
            //this.summDetailGrid.removeBtn.setDisabled(sm.getCount() < 1);
        });
    },
    ShowMode: function(n) {
        if(n){
            this.modeToggler1.enable();
            this.modeToggler2.disable();
            this.execAndPayStore.groupBy('wap_type_id');
            this.execAndPayStore.sort('isplan', 'DESC');
        } else {
            this.modeToggler1.disable();
            this.modeToggler2.enable();
            this.execAndPayStore.groupBy('isplan');
            this.execAndPayStore.sort('wap_type_id', 'ASC');
        }
    },
    getContractDetail: function() {
        this.summDetailStore.removeAll(false);
        this.execAndPayStore.baseParams = { contract_id: this.cnt_id};
        this.execAndPayStore.load();
    },
    getSummDetail: function(mm, type) {
        this.summDetailStore.baseParams = {doc_type_id: type, contract_id: this.cnt_id, yy: this.year, mm: mm };
        this.summDetailStore.load();
    },
    updateSummCell: function(val) {
        var rec = this.execAndPayStore.data.items[this.SelectedCell.RowIdx];
        rec.set(this.SelectedCell.dataIndex, val);
        this.execAndPayStore.commitChanges();
    },
    deleteDocument: function(doc_id) {
        this.rEditor.stopEditing();
        var r = this.summDetailGrid.getSelectionModel().getSelected();
        var th = this;
        if( r ) {
            Ext.MessageBox.confirm('Внимание !!!', 'Вы уверены что хотите удалить документ "'+r.data.document+ '" ?',
                function(btn) {
                    if (btn == 'yes'){
                        var th = this;
                        Ext.Ajax.request({
                            url: 'main?action=deleteDocument',
                            params: r.data,
                            scope: th,
                            callback: function(options, success, response) {
                                var ansv = Ext.decode(response.responseText);
                                if(ansv.success === true) {
                                    th.updateSummCell(ansv.new_summ);
                                    th.summDetailStore.remove(r);
                                } else { error_mes('Ошибка',  ansv.error); }
                            }
                        });
                    }
                }, this
            );
        } else { error_mes('Внимание !!!', 'Вы не выбрали запись для удаления.'); }
    },
    paint: function(value, metaData, record, rowIndex, colIndex, store) {
      return ComAmountRenderer(value,2);
   },
   total:function(value, metaData, record, rowIndex, colIndex, store) {
        var val = parseFloat(parseFloat(record.data.m01)+parseFloat(record.data.m02)+parseFloat(record.data.m03)+parseFloat(record.data.m04)+
            parseFloat(record.data.m05)+parseFloat(record.data.m06)+parseFloat(record.data.m07)+parseFloat(record.data.m08)+
            parseFloat(record.data.m09)+parseFloat(record.data.m10)+parseFloat(record.data.m11)+parseFloat(record.data.m12));
        if(rowIndex<4) {
            return '<b>'+sprintf('%01.2f', parseFloat( val ) )+'</b>';
        } else {
            if( val ==0 ) return '<span class="greyDigit"><b>'+sprintf('%01.2f', parseFloat( val ) )+'</b></span>';
            if( val > 0 ) return '<span class="greenDigit"><b>'+sprintf('%01.2f', parseFloat( val ) )+'</b></span>';
            if( val < 0 ) return '<span class="redDigit"><b>'+sprintf('%01.2f', parseFloat( val ) )+'</b></span>';
        }
   },
   TypeCollRender: function(val) {
       return (val==1) ? 'Отработки:' : 'Оплаты:';
   },
   getPlanTitle: function(value, metaData, record, rowIndex, colIndex, store) {
       return (record.data.isplan) ? 'План' : 'Факт' ;
   }
});